#!/bin/bash

set -x

# 对外开放的端口
RSYNC_OUTER_SERVER=0.0.0.0:7873

# 与rsycn配置一致
RSYNC_INNER_SERVER=127.0.0.1:6873

config_server()
{
	mkdir -p /etc/stunnel

	cat > /etc/stunnel/stunnel.conf <<EOF
setuid = nobody
setgid = nobody

#debug = 7
#foreground = yes 

pid = /var/run/stunnel/stunnel.pid
output = /var/log/stunnel/stunnel.log

cert = /etc/stunnel/server.crt
key = /etc/stunnel/server.key
CAfile = /etc/stunnel/client.crt

verify = 3


[rsync]
accept = $RSYNC_OUTER_SERVER
connect = $RSYNC_INNER_SERVER
EOF

	cat > /etc/stunnel/prepare.sh <<EOF
#!/bin/bash

mkdir -p /var/run/stunnel /var/log/stunnel
chown nobody:nobody /var/run/stunnel /var/log/stunnel
EOF
	chmod 755 /etc/stunnel/prepare.sh

	cat > /lib/systemd/system/stunnel.service <<EOF
[Unit]
Description=stunnel daemon
ConditionPathExists=/etc/stunnel/stunnel.conf
After=network.target

[Service]
Type=forking
ExecStartPre=-/etc/stunnel/prepare.sh
ExecStart=/usr/local/bin/stunnel /etc/stunnel/stunnel.conf
ExecStop=/usr/bin/pkill -9 stunnel

# Give up if ping don't get an answer
TimeoutSec=600

Restart=always
EOF

	systemctl enable stunnel.service
	systemctl restart stunnel.service
}

config_logrotate()
{
	if [ ! -f /etc/cron.daily/logrotate -o ! -f /etc/logrotate.conf ]; then
		echo "ERROR: miss logrotate && crontab"
		return
	fi

	cat > /etc/logrotate.d/stunnel <<EOF
/var/log/stunnel/stunnel.log {
	daily
	maxsize 100M
	rotate 7
	copytruncate
	compress
	delaycompress
	notifempty
	missingok
}
EOF
}

config_server
config_logrotate
